package require ftp

# Defaults
set recursive 0
set showhelp [expr $argc == 0]
set usepwd 0

for {set i 0} {$i <= $argc} {incr i} {
    switch -glob -- [lindex $argv $i] {
        -r* {
            set recursive 1
        }
        -f* {
            set file [lindex $argv [incr i]]
        }
        -h* {
            set showhelp 1
        }
        -pwd {
            set usepwd 1
        }
    }
}

if {!$usepwd && ![info exists file]} {
    set showhelp 1
}

if {$showhelp} {
    puts "\nUsage:\n"
    puts "tclftp -pwd | -f, -file <file> ?-r, -recursive?"
}

# Parse hosts file
set user $env(USER)
set f [open /Users/$user/.tclftp_hosts]
array set config [read $f]
close $f

if {![info exists config(host)] ||
    ![info exists config(user)] ||
    ![info exists config(pass)]} {
    return -code error "tclftp: missing one of: host, user, password"
} elseif {$showhelp} {
    puts "\nConfig (/Users/$user/.tclftp_hosts):\n"
    foreach {nm val} [array get config] {
        if {$nm != "pass"} {
            puts "$nm : $val"
        }
    }
    puts ""
}

if {$showhelp} {
    return 0
}

if {![info exists config(localsrcdir)] || ![info exists config(hostsrcdir)]} {
    return -code error "tclftp: config(localsrcdir) and config(hostsrcdir) are required in config file"
}
set pwd [exec pwd]
# get the path relative to $config(localsrcdir)
set regsub [subst {regsub $config(localsrcdir)/ $pwd {} path}]
eval $regsub

proc putFile {file} {
    puts "cmd: put $file"
    putResponse [::ftp::Put $::sock $file]
}

proc putResponse {response} {
    if {$response} {
        puts "<< success"
    } else {
        puts "<< fail"
    }
}

puts "Connecting to '$config(host)'"
set sock [ftp::Open $config(host) $config(user) $config(pass)]

puts "cmd: cd $config(hostsrcdir)/$path:"
set response [::ftp::Cd $sock $config(hostsrcdir)/$path]
putResponse $response
set continue 1
if {!$response} {
    puts "*** remote dir '$config(hostsrcdir)/$path' not found. Closing connection..."
    ftp::Close $sock
    return 0
}

if {[info exists file]} {
    putFile $file
} else {
    foreach fname [glob -directory $pwd -- *.java] {
        putFile $fname
    }
}

puts "Closing connection..."
ftp::Close $sock

puts "Done."
